package com.penghk.earth.util.excel;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * 导出时传入list<T>,即可实现导出为一个excel,其中每个对象Ｔ为Excel中的一条记录.
 *
 * @param <T>
 */
public class ExcelUtil<T> {
    Logger logger = LoggerFactory.getLogger(ExcelUtil.class);

    Class<T> clazz;

    public ExcelUtil(Class<T> clazz) {
        this.clazz = clazz;
    }


    public boolean exportExcel(List<T> lists[], String[] sheetNames, OutputStream out) {

        if (lists.length != sheetNames.length) {
            System.out.println("数组长度不一致");
            return false;
        }

        HSSFWorkbook workbook = new HSSFWorkbook();// 产生工作薄对象

        for (int ii = 0; ii < lists.length; ii++) {
            HSSFSheet sheet = workbook.createSheet();// 产生工作表对象
            List<T> list = lists[ii];
            String sheetName = sheetNames[ii];
            workbook.setSheetName(ii, sheetName);

            List<Field> fields = getMappedFiled(clazz, null);
            HSSFRow row;
            HSSFCell cell;// 产生单元格
            HSSFCellStyle style = workbook.createCellStyle();
            style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
            style.setFillBackgroundColor(HSSFColor.GREY_40_PERCENT.index);
            row = sheet.createRow(0);
            for (int i = 0; i < fields.size(); i++) {
                Field field = fields.get(i);
                ExcelVoAttribute excelVoAttribute = field.getAnnotation(ExcelVoAttribute.class);
                int cellIndex = Integer.parseInt(excelVoAttribute.column());
                cell = row.createCell(cellIndex);
                cell.setCellValue(excelVoAttribute.name());
                cell.setCellType(HSSFCell.CELL_TYPE_STRING);// 设置列中写入内容为String类型
                cell.setCellStyle(style);
            }

            for (int j = 0; j < list.size(); j++) {
                row = sheet.createRow(j + 1);
                T vo = list.get(j);
                for (Field field : fields) {
                    field.setAccessible(true);
                    ExcelVoAttribute attr = field.getAnnotation(ExcelVoAttribute.class);
                    if (attr.isExport()) {
                        cell = row.createCell(Integer.parseInt(attr.column()));
                        cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                        try {
                            cell.setCellValue(field.get(vo) == null ? "" : String.valueOf(field.get(vo)));
                        } catch (IllegalAccessException e) {
                            logger.error("无法访问属性元素");
                            e.printStackTrace();
                        }
                    }
                }
            }
        }

        try {
            workbook.write(out);
            workbook.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    private List<Field> getMappedFiled(Class<? super T> clazz, List<Field> fields) {
        if (fields == null) {
            fields = new ArrayList<>();
        }
        Field[] fields1 = clazz.getDeclaredFields();
        for (Field field : fields1) {
            if (field.isAnnotationPresent(ExcelVoAttribute.class)) {
                fields.add(field);
            }
        }
        if (clazz.getSuperclass() != null && clazz.getSuperclass() != Object.class) {
            getMappedFiled(clazz.getSuperclass(), fields);
        }
        return fields;
    }

}
